package com.scmt.hmzd.utils;

import cn.hutool.json.JSONObject;
import com.scmt.hmzd.entity.AccessToken;
import org.dom4j.DocumentException;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import javax.servlet.http.HttpServletRequest;

public class WxUtils {

    //获取token
    private static final String appid = "wxa7e819b05ce698b3";
    private static final String secret = "5952f07add282f56768ceb6fc284a48c";
    private static final String GET_TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET";
    private static final String GENERATE_SCHEME_URL = "https://api.weixin.qq.com/wxa/generatescheme?access_token=ACCESS_TOKEN";
    private static AccessToken at;


    public static AccessToken getAccessToken() {
        String url = GET_TOKEN_URL.replace("APPID", appid).replace("APPSECRET", secret);
        String url1 = Utils.getUrl(url);
        JSONObject jb = new JSONObject(url1);
        //回传内容
        String accessToken = (String) jb.get("access_token");
        String expiresIn = jb.get("expires_in").toString();
        at = new AccessToken(accessToken, expiresIn);
        return at;
    }


    /**
     * 生成由[A-Z,0-9]生成的随机字符串
     * @param length  欲生成的字符串长度
     * @return
     */
    public static String getRandomString(int length){
        Random random = new Random();

        StringBuffer sb = new StringBuffer();

        for(int i = 0; i < length; ++i){
            int number = random.nextInt(2);
            long result = 0;

            switch(number){
                case 0:
                    result = Math.round(Math.random() * 25 + 65);
                    sb.append(String.valueOf((char)result));
                    break;
                case 1:

                    sb.append(String.valueOf(new Random().nextInt(10)));
                    break;
            }
        }
        return sb.toString();
    }


    public Map<String, Object> getElementValueToMap(InputStream in) {
        SAXReader reader = new SAXReader();
        Document document = null;
        try {
            document = reader.read(in);
        } catch (DocumentException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        Element root = document.getRootElement();
        HashMap<String, Object> stringObjectHashMap = new HashMap<>();
        List<Element> childElements = root.elements();
        for (Element child : childElements) {
            stringObjectHashMap.put(child.getName(), child.getStringValue());
        }
        return stringObjectHashMap;
    }


    /**
     * 获取请求IP地址
     */
    public String getIpAddr(HttpServletRequest request) {
        String ipAddress = null;
        ipAddress = request.getHeader("x-forwarded-for");
        if ((ipAddress == null) || (ipAddress.length() == 0)
                || ("unknown".equalsIgnoreCase(ipAddress))) {
            ipAddress = request.getHeader("Proxy-Client-IP");
        }
        if ((ipAddress == null) || (ipAddress.length() == 0)
                || ("unknown".equalsIgnoreCase(ipAddress))) {
            ipAddress = request.getHeader("WL-Proxy-Client-IP");
        }
        if ((ipAddress == null) || (ipAddress.length() == 0)
                || ("unknown".equalsIgnoreCase(ipAddress))) {
            ipAddress = request.getRemoteAddr();
            if (ipAddress.equals("127.0.0.1")) {
                InetAddress inet = null;
                try {
                    inet = InetAddress.getLocalHost();
                } catch (UnknownHostException e) {
                    e.printStackTrace();
                }
                ipAddress = inet.getHostAddress();
            }
        }
        if ((ipAddress != null) && (ipAddress.length() > 15)) {
            if (ipAddress.indexOf(",") > 0) {
                ipAddress = ipAddress.substring(0, ipAddress.indexOf(","));
            }
        }
        return ipAddress;
    }


    /**
     * 通过返回IO流获取支付地址
     *
     * @param in
     * @return
     */
    public String getElementValue(InputStream in, String key) {
        SAXReader reader = new SAXReader();
        Document document = null;
        try {
            document = reader.read(in);
        } catch (DocumentException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        Element root = document.getRootElement();
        List<Element> childElements = root.elements();
        for (Element child : childElements) {
            System.out.println(child.getName() + ":" + child.getStringValue());
            if (key.equals(child.getName())) {
                return child.getStringValue();
            }
        }
        return null;
    }


}
